package com.itheima.web.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class AuthorFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest)req;
        ServletResponse response = (ServletResponse)resp;

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        //1.获取正在访问的URI
        String uri = request.getRequestURI();

        //2.获取用户可以操作的模块的地址
        String curls = (String)request.getSession().getAttribute("curls");


        //3.可以直接访问的资源
        if(uri.contains("login") || uri.contains("index") || uri.contains("js") || uri.contains("img") || uri.contains("css") || uri.contains("gg.html") ){
            chain.doFilter(req,resp);
        }else{
            //4.判断有没有登陆
            if(request.getSession().getAttribute("user")==null){
                response.getWriter().println("<h1><a href='/login.jsp'>请登陆</a> </h1>");
            }else{
                //5.判断是否有权限
                if(curls.contains(uri)){
                    chain.doFilter(req, resp);
                }else{
                    response.getWriter().println("<h1>权限不足，请联系管理员</h1>");
                }
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
